<template>
  <MyModal
    ref="$form"
    :model-form="model"
    :width="1100"
    :no-padding="true"
    :disabled="type === 'view'"
    @submit="handleSubmit"
  >
    <div class="flex flex-col gap-10">
      <div class="grid grid-cols-2 gap-x-16 bg-#F4F5F7 p-16">
        <n-form-item
          label="项目名称"
          path="projectName"
          :rule="[{ required: true, message: '请输入项目名称！' }]"
        >
          <n-input v-model:value="model.projectName" clearable :maxlength="50" />
        </n-form-item>
        <div class="flex gap-8">
          <n-form-item
            label="项目版本"
            path="projectVersion"
            :rule="[{ required: true, message: '请输入大版本号！' }]"
          >
            <AsyncSelect v-model:value="model.projectVersion" :options="10" :clearable="false" />
          </n-form-item>
          <n-form-item
            path="projectVersionMinor"
            :rule="[{ required: true, message: '请输入小版本号！' }]"
          >
            <AsyncSelect
              v-model:value="model.projectVersionMinor"
              :options="10"
              :clearable="false"
            />
          </n-form-item>
        </div>
        <n-form-item
          label="项目类型"
          path="projectType"
          :rule="[{ required: true, message: '请选择项目类型！' }]"
        >
          <AsyncSelect v-model:value="model.projectType" options="PROJECT_TYPE" multiple />
        </n-form-item>
        <n-form-item label="项目等级" path="projectLevel">
          <AsyncSelect v-model:value="model.projectLevel" options="PROJECT_LEVEL" />
        </n-form-item>
        <n-form-item label="项目描述" path="projectResume">
          <n-input
            v-model:value="model.projectResume"
            clearable
            :maxlength="300"
            show-count
            type="textarea"
            :autosize="{
              minRows: 3,
            }"
          />
        </n-form-item>
        <n-form-item label="项目注意" path="projectNote">
          <n-input
            v-model:value="model.projectNote"
            clearable
            :maxlength="300"
            show-count
            type="textarea"
            :autosize="{
              minRows: 3,
            }"
          />
        </n-form-item>
      </div>
      <div class="grid grid-cols-2 gap-x-16 bg-#F4F5F7 p-16">
        <n-form-item label="是否立即启动" path="isStartNow">
          <n-radio-group v-model:value="model.isStartNow" :disabled="lockStart">
            <n-radio :value="false">否</n-radio>
            <n-radio :value="true">是</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="客户提测节点" path="customerTestNode">
          <n-date-picker
            v-model:formatted-value="model.customerTestNode"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm"
            :time-picker-props="{ format: 'HH:mm' }"
            placeholder="选择时间"
            clearable
          />
        </n-form-item>
        <n-form-item label="内部提测节点" path="insideTestNode">
          <n-date-picker
            v-model:formatted-value="model.insideTestNode"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm"
            :time-picker-props="{ format: 'HH:mm' }"
            placeholder="选择时间"
            clearable
          />
        </n-form-item>
        <n-form-item label="上线节点" path="releaseTestNode">
          <n-date-picker
            v-model:formatted-value="model.releaseTestNode"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm"
            :time-picker-props="{ format: 'HH:mm' }"
            placeholder="选择时间"
            clearable
          />
        </n-form-item>
        <n-form-item label="交付物说明" path="deliverablesDescription">
          <n-input
            v-model:value="model.deliverablesDescription"
            clearable
            :maxlength="300"
            show-count
            type="textarea"
            :autosize="{
              minRows: 3,
            }"
          />
        </n-form-item>
        <n-form-item label="交付物附件" path="deliverablesFileDtoList">
          <FileUpload v-model="model.deliverablesFileDtoList" color="#FFF" />
        </n-form-item>
        <n-form-item label="任务环节" path="taskStage">
          <AsyncSelect v-model:value="model.taskStage" options="TASK_STAGE" multiple />
        </n-form-item>
      </div>
      <div class="bg-#F4F5F7 p-16">
        <n-form-item label="上传附件" path="projectFileDtoList">
          <FileUpload v-model="model.projectFileDtoList" color="#FFF" />
        </n-form-item>
      </div>
      <div class="bg-#F4F5F7 p-16">
        <n-form-item label="研发负责组" path="developGroup">
          <AsyncSelect
            v-model:value="model.developGroup"
            label-key="name"
            value-key="deptId"
            :options="devDeptOptions"
            placeholder="请设置研发负责组"
            style="width: 400px"
          />
          <div v-if="model.developGroup" class="ml-20">
            (组长：{{ groupLeader.leaderName || '暂无' }})
          </div>
        </n-form-item>
        <n-form-item
          label="人员安排"
          path="projectPersonDtoList"
          :rule="{ validator: validatorPerson }"
        >
          <Member v-model="model.projectPersonDtoList" :group-id="groupLeader?.deptId || ''" />
        </n-form-item>
      </div>
    </div>
  </MyModal>
</template>
<script setup lang="jsx">
import { useCrudPro } from '@/hooks/useCrudPro'
import { changeToProject } from '@/api/niche'
import * as projectApi from '@/api/project'
import { formatToIds, formatToSel } from '@/utils/format'
import { onBeforeMount } from 'vue'
defineOptions({ name: 'ProjectForm' })
const props = defineProps({
  opportunityId: {
    type: String,
    default: '',
  },
  defaultName: {
    type: String,
    default: '',
  },
  projectPid: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(['result'])
const groupLeader = ref({})
const devDeptOptions = ref([])
async function getDevDeptOptions() {
  const { data } = await projectApi.devDeptList()
  devDeptOptions.value = data
}
function validatorPerson(_, value, callback) {
  if (Array.isArray(value) && value.length) {
    if (value.some((item) => !item.personId)) {
      callback(new Error('请选择人员!'))
    } else if (value.some((item) => !item.executeRangeCode.length)) {
      callback(new Error('请选择执行范围!'))
    } else if (value.length !== [...new Set(value.map((item) => item.personId))].length) {
      callback(new Error('存在重复人员!'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const lockStart = ref(false)
const { type, model, $form, handleAdd, handleEdit, handleDelete, handleSubmit } = useCrudPro({
  name: '项目',
  initForm: {
    id: null,
    projectName: null,
    projectVersion: 0,
    projectVersionMinor: 0,
    projectType: null,
    projectLevel: null,
    projectResume: null,
    projectNote: null,
    isStartNow: false,
    customerTestNode: null,
    insideTestNode: null,
    releaseTestNode: null,
    deliverablesDescription: null,
    deliverablesFileDtoList: [],
    taskStage: null,
    projectFileDtoList: [],
    developGroup: null,
    projectPersonDtoList: [],
  },
  apis: {
    add: (params) => {
      const { opportunityId, projectPid } = props
      if (opportunityId) {
        return changeToProject({ ...params, opportunityId })
      } else if (projectPid) {
        return projectApi.addVersion({ ...params, projectPid })
      } else {
        return projectApi.add(params)
      }
    },
    edit: projectApi.edit,
    del: ({ id }) => projectApi.del({ id }),
    info: ({ id }) =>
      projectApi.info({ id }).then((res) => {
        lockStart.value = res.data.projectPhase !== 'TO_BE_STARTED'
        res.data.projectType = formatToSel(res.data.projectType)
        res.data.taskStage = formatToSel(res.data.taskStage)
        res.data.projectPersonDtoList = (res?.data?.projectPersonDtoList || []).map((item) => ({
          ...item,
          executeRangeCode: formatToSel(item.executeRangeCode),
        }))
        return res.data
      }),
  },
  formatParams(params) {
    params.projectType = formatToIds(params.projectType)
    params.taskStage = formatToIds(params.taskStage)
    params.projectPersonDtoList = (params?.projectPersonDtoList || []).map((item) => ({
      ...item,
      executeRangeCode: formatToIds(item.executeRangeCode),
    }))
    return params
  },
  handleChange(actionType) {
    emits('result', actionType)
  },
  onShow() {
    lockStart.value = false
  },
  onReady(type) {
    if (type === 'add' && props.defaultName) {
      model.value.projectName = props.defaultName
    }
    if (type === 'add' && !props.projectPid) {
      model.value.projectVersion = 1
    }
  },
})
onBeforeMount(() => {
  getDevDeptOptions()
})
watchEffect(() => {
  groupLeader.value =
    devDeptOptions.value?.find((item) => item.deptId === model.value.developGroup) || {}
})
defineExpose({
  handleAdd,
  handleEdit,
  handleDelete,
  setState: (...arg) => $form.value.setState(...arg),
})
</script>
<style lang="scss" scoped></style>
